const db = require("../common/db/index")

module.exports = {
  // 添加评论
  add(article_id, user_id, content, parent_id, createAt, status) {
    return new Promise(async (resolve, reject) => {
      try {
        const sql = 'INSERT INTO pre_comment (article_id, user_id, content, parent_id, createAt, status) VALUES (?, ?, ?, ?, ?, ?)';
        const result = await db.query(sql, [article_id, user_id, content, parent_id || 0, createAt, status || 'published']);
        resolve({
          code: 200,
          msg: "评论成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "评论失败",
          err: err
        });
      }
    });
  },

  // 获取文章评论列表（支持分页）
  getList(article_id, page_num, page_size) {
    return new Promise(async (resolve, reject) => {
      try {
        // 先获取总数（只统计顶级评论，parent_id = 0）
        const countSql = 'SELECT count(*) as total FROM pre_comment WHERE article_id = ? AND status = ? AND parent_id = 0';
        const countResult = await db.query(countSql, [article_id, 'published']);
        const total = countResult[0].total;

        // 分页查询（只查询顶级评论，parent_id = 0）
        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size));
        let page_size2 = parseInt(page_size);
        const sql = `
                    SELECT c.*, u.username, u.imgUrl 
                    FROM pre_comment c 
                    LEFT JOIN pre_user u ON c.user_id = u.id 
                    WHERE c.article_id = ? AND c.status = ? AND c.parent_id = 0
                    ORDER BY c.createAt DESC 
                    LIMIT ${page_num2}, ${page_size2}
                `;
        const data = await db.query(sql, [article_id, 'published']);

        // 获取每条评论的回复
        for (let comment of data) {
          const replySql = `
                        SELECT r.*, u.username, u.imgUrl, 
                               parent_user.username as parent_username
                        FROM pre_comment r 
                        LEFT JOIN pre_user u ON r.user_id = u.id 
                        LEFT JOIN pre_comment parent_comment ON r.parent_id = parent_comment.id
                        LEFT JOIN pre_user parent_user ON parent_comment.user_id = parent_user.id
                        WHERE r.parent_id = ? AND r.status = ? 
                        ORDER BY r.createAt ASC
                    `;
          comment.replies = await db.query(replySql, [comment.id, 'published']);
        }

        resolve({
          code: 200,
          msg: "获取评论列表成功",
          total: total,
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取评论列表失败",
          err: err
        });
      }
    });
  },

  // 删除评论（软删除，修改状态）
  delete(id, user_id) {
    return new Promise(async (resolve, reject) => {
      try {
        // 先检查评论是否存在且属于该用户
        const checkSql = 'SELECT * FROM pre_comment WHERE id = ? AND user_id = ?';
        const checkResult = await db.query(checkSql, [id, user_id]);

        if (checkResult.length === 0) {
          resolve({
            code: 403,
            msg: "无权删除此评论"
          });
          return;
        }

        // 软删除：修改状态为deleted
        const sql = 'UPDATE pre_comment SET status = ? WHERE id = ?';
        const result = await db.query(sql, ['deleted', id]);

        resolve({
          code: 200,
          msg: "删除评论成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "删除评论失败",
          err: err
        });
      }
    });
  },

  // 获取用户的所有评论
  getUserComments(user_id, page_num, page_size) {
    return new Promise(async (resolve, reject) => {
      try {
        const countSql = 'SELECT count(*) as total FROM pre_comment WHERE user_id = ? AND status = ?';
        const countResult = await db.query(countSql, [user_id, 'published']);
        const total = countResult[0].total;

        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size));
        let page_size2 = parseInt(page_size);
        const sql = `
                    SELECT c.*, a.title as article_title 
                    FROM pre_comment c 
                    LEFT JOIN pre_article a ON c.article_id = a.id 
                    WHERE c.user_id = ? AND c.status = ? 
                    ORDER BY c.createAt DESC 
                    LIMIT ${page_num2}, ${page_size2}
                `;
        const data = await db.query(sql, [user_id, 'published']);

        resolve({
          code: 200,
          msg: "获取用户评论成功",
          total: total,
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取用户评论失败",
          err: err
        });
      }
    });
  },

  // 获取所有评论列表（管理员用，包含文章标题和用户名）
  getAllComments(page_num, page_size, keyword) {
    return new Promise(async (resolve, reject) => {
      try {
        let countSql = 'SELECT count(*) as total FROM pre_comment c LEFT JOIN pre_article a ON c.article_id = a.id LEFT JOIN pre_user u ON c.user_id = u.id WHERE 1=1';
        let sql = `
          SELECT c.*, a.title as article_title, u.username 
          FROM pre_comment c 
          LEFT JOIN pre_article a ON c.article_id = a.id 
          LEFT JOIN pre_user u ON c.user_id = u.id 
          WHERE 1=1
        `;
        let params = [];

        // 如果有搜索关键词，添加搜索条件
        if (keyword && keyword.trim()) {
          const keywordParam = `%${keyword.trim()}%`;
          countSql += ' AND (c.content LIKE ? OR a.title LIKE ? OR u.username LIKE ?)';
          sql += ' AND (c.content LIKE ? OR a.title LIKE ? OR u.username LIKE ?)';
          params = [keywordParam, keywordParam, keywordParam];
        }

        // 获取总数
        const countResult = await db.query(countSql, params);
        const total = countResult[0].total;

        // 分页查询
        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size));
        let page_size2 = parseInt(page_size);
        sql += ` ORDER BY c.createAt DESC LIMIT ${page_num2}, ${page_size2}`;

        const data = await db.query(sql, params);

        resolve({
          code: 200,
          msg: "获取评论列表成功",
          total: total,
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取评论列表失败",
          err: err
        });
      }
    });
  },

  // 隐藏评论（修改状态为hidden）
  hideComment(id) {
    return new Promise(async (resolve, reject) => {
      try {
        const sql = 'UPDATE pre_comment SET status = ? WHERE id = ?';
        const result = await db.query(sql, ['hidden', id]);

        resolve({
          code: 200,
          msg: "隐藏评论成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "隐藏评论失败",
          err: err
        });
      }
    });
  },

  // 恢复评论（修改状态为published）
  restoreComment(id) {
    return new Promise(async (resolve, reject) => {
      try {
        const sql = 'UPDATE pre_comment SET status = ? WHERE id = ?';
        const result = await db.query(sql, ['published', id]);

        resolve({
          code: 200,
          msg: "恢复评论成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "恢复评论失败",
          err: err
        });
      }
    });
  },

  // 管理员删除评论（可以删除任何评论，硬删除）
  adminDelete(id) {
    return new Promise(async (resolve, reject) => {
      try {
        // 先删除该评论的所有回复（级联删除）
        const deleteRepliesSql = 'DELETE FROM pre_comment WHERE parent_id = ?';
        await db.query(deleteRepliesSql, [id]);

        // 硬删除：直接从数据库中删除评论记录
        const sql = 'DELETE FROM pre_comment WHERE id = ?';
        const result = await db.query(sql, [id]);

        resolve({
          code: 200,
          msg: "删除评论成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "删除评论失败",
          err: err
        });
      }
    });
  }
}

